/*
 * Copyright (C) 2013 Brett Wooldridge
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jse;

import java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;

import sun.misc.Unsafe;

public final class Unsafes
{
   private static final Unsafe UNSAFE;
   private static long ADDRESS_FIELD_OFFSET;

   static {
      try {
         Field f = Unsafe.class.getDeclaredField("theUnsafe");
         f.setAccessible(true);
         UNSAFE = (Unsafe) f.get(null);
      }
      catch (Exception e) {
         throw new RuntimeException(e);
      }
      try {
//         Class<?> clazz = Class.forName("java.nio.DirectByteBuffer");
         Class<?> clazz = Class.forName("java.nio.Buffer");
         Field addressField = clazz.getDeclaredField("address");
         ADDRESS_FIELD_OFFSET = UNSAFE.objectFieldOffset(addressField);
      }
      catch (Throwable e) {
    	  e.printStackTrace();
         throw new RuntimeException("Unable to obtain reference to java.nio.DirectByteBuffer constructor", e);
      }
   }

   public static Unsafe getUnsafe()
   {
      return UNSAFE;
   }
   /**
    * 根据类直接获取对象
    * @param clazz<T> 泛型任意对象
    * @return
    */
   public static <T> T obj(Class<T> clazz) {
	   try {
		return (T)UNSAFE.allocateInstance(clazz);
	} catch (InstantiationException e) {
		return null;
	}
   }
   
   /**
    * 这个获取地址的思路是,调用getInt，
    * 获取array中偏移16字节位置的值，也就是从16位置开始取4字节，其实也就是获取到了Object[0]的值，肯定是一个地址
    * <p>
    * 但这个地址在开启指针压缩的jvm中是还需要再放大8倍才是实际地址
    */
   public static long getAddress(Object target) {
	   if(target instanceof Buffer) {
		   return getAddress((ByteBuffer)target);
	   }
       Object[] array = new Object[1];
       array[0] = target;
       //这里其实有两个情况，如果jvm开启压缩制作，地址只占有4字节，也可以调用getInt
       long anInt = UNSAFE.getLong(array, 16);
       /**
        * 如果开启指针压缩，则上一步获取的地址并不是实际地址，
        * 指针压缩是，内存被jvm按照8字节（不是8比特）分块，anInt就代表是第几块内存
        *
        * 所以左移3次，放大八倍就可以获得到实际内存地址，当然这里也可能不是3，只是目前在我的电脑上查看是3
        *
        * 至于为啥还要加个0，这个我也不清楚,但好像和调试有关
        *
        * */
       anInt = 0 + (anInt << 3);
       return anInt;
   }
   public static long getAddress(ByteBuffer byteBuffer)
   {
      return UNSAFE.getLong(byteBuffer, ADDRESS_FIELD_OFFSET);
   }
   
   /**
    * 用于获取某个字段相对Java对象的“起始地址”的偏移量int
    * @param f
    * @return
    */
   public static long objectFieldOffset(Field f) {
	   return UNSAFE.objectFieldOffset(f);
   }
   /**
    * 用于获取某个字段相对Java对象的“起始地址”的偏移量int
    * @param clazz
    * @param fieldName
    * @return
    */
   public static long objectFieldOffset(Class<?> clazz,String fieldName) {
	   try {
		return objectFieldOffset(clazz.getDeclaredField(fieldName));
	} catch (NoSuchFieldException | SecurityException e) {
		throw new RuntimeException(e);
	}
   }
   /**
    * 读取传入对象o在内存中偏移量为offset位置的值与期望值expected作比较。相等就把x值赋值给offset位置的值。方法返回true。
    * @param o
    * @param offset
    * @param expected
    * @param x
    * @return
    */
   public static boolean compareAndSwapInt(Object o, long offset,int expected,int x) {
	   return UNSAFE.compareAndSwapInt(o,offset,expected,x);
   }
   /**
    * 读取传入对象o在内存中偏移量为offset位置的值与期望值expected作比较。相等就把x值赋值给offset位置的值。方法返回true。
    * @param o
    * @param offset
    * @param expected
    * @param x
    * @return
    */
   public static boolean compareAndSwapObject(Object o, long offset,Object expected,Object x) {
	   return UNSAFE.compareAndSwapObject(o,offset,expected,x);
   }
   /**
    * 
    * @param directByteBuffer 直接字节缓冲区
    */
   public static void cleaner(ByteBuffer directByteBuffer) {
	   UNSAFE.invokeCleaner(directByteBuffer);
   }

//   public static ByteBuffer wrapNativeMemory(long address, int capacity)
//   {
//      try {
//         return (ByteBuffer) DIRECT_BYTEBUFFER_CONSTRUCTOR.invokeExact(new Object[] { address, capacity });
//      }
//      catch (Throwable e) {
//         throw new RuntimeException("Unable to create wrapping DirectByteBuffer");
//      }
//   }

   
}